
// https://promisesaplus.com/ 官方文档

// const MyPromise = require('./MyPromise.js');
// const MyPromise = require('./MyPromise2.js');
const MyPromise = require('./MyPromise3.js');
const MyPromiseTools = require('./myAll&myRace.js');

// let promise = new Promise((resolve, reject) => { // exector
//   // resolve('Success');
//   // reject('Error');
//   // throw new Error('Exception: Error');
//   setTimeout(() => {
//     resolve('timeout: Success');
//   }, 2000)
// });

// let promise = new MyPromise((resolve, reject) => {
//   // resolve('MyPromise: Success');
//   // reject('MyPromise: Error');
//   // throw new Error('Exception: Error MyPromise');
//   setTimeout(() => {
//     resolve('timeout: Success');
//   }, 2000)
// });

// promise.then(value => {
//   console.log('Fulfilled1: ' + value);
// }, reason => {
//   console.log('Rejected1: '+ reason);
// });

// promise.then(value => {
//   console.log('Fulfilled2: ' + value);
// }, reason => {
//   console.log('Rejected2: '+ reason);
// });


let promise1 = new MyPromise((resolve, reject) => {
  resolve('promise1');
  // reject('promise1 Error');
})

let promise2 = promise1.then(value => {
  // return value + ' -> then -> promise2';
  // return promise2;
  // return Promise.resolve(value + ' -> then -> promise2');
  return new MyPromise((resolve, reject) => {
    // resolve(value + ' -> then -> promise2');
    // reject();
    // return new Error('Error');
    // resolve('new Promise resolve');
    setTimeout(() => {
      // resolve('new Promise resolve');
      resolve(new MyPromise((resolve, reject) => {
        // resolve('new Promise resolve');
        resolve(new MyPromise((resolve, reject) => {
          resolve('new Promise resolve');
        }))
      }))
    }, 2000)
  });
  // return new Error('Error');
  // throw new Error('promise2 throw error');
  // return 'Then Promise';
}, reason => {
  return reason;
})

promise2.then().then().then().then(value => {
  console.log(value);
  // throw Error('Error...')
}, reason => {
  console.log(reason);
})
.catch(e => {
  console.log(e);
})



let p1 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve(1)
  }, 1000)
})
let p2 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve(2)
  }, 2000)
})
let p3 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve(3)
  }, 3000)
})

// Promise.all([p3, p1, p2]).then(res => {
//   console.log(res) // [3, 1, 2]
// })
MyPromiseTools.all([p3, p1, p2]).then(res => {
  console.log(res) // [3, 1, 2]
})

// Promise.race([p3, p1, p2]).then(res => {
//   console.log(res) // 1
// })
MyPromiseTools.race([p3, p1, p2]).then(res => {
  console.log(res) // 1
})